using System;
using System.Collections.Generic;
using JetBrains.Annotations;

namespace EventBus
{
    public partial class EventBusImpl : IEventBus
    {
        private readonly Dictionary<string, Broadcast> _broadcasts = new Dictionary<string, Broadcast>();
        private readonly Func<Broadcast> _broadcastFactory;

        public EventBusImpl(Func<Broadcast> broadcastFactory)
        {
            _broadcastFactory = broadcastFactory;
        }

        private Broadcast GetOrCreateBroadcast(string eventName)
        {
            if (_broadcasts.TryGetValue(eventName, out var broadcast))
            {
                return broadcast;
            }

            var newBroadcast = _broadcastFactory();
            _broadcasts.Add(eventName, newBroadcast);
            return newBroadcast;
        }
        
        private void ListenImpl(string eventName, object callback)
        {
            var listener = GetOrCreateBroadcast(eventName);
            listener.AddListener(eventName, callback);
        }

        private void RemoveBroadcast(string eventName)
        {
            _broadcasts.Remove(eventName);
        }
    }
}